package com.example.service.Imp;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.VO.LoginUser;
import com.example.entiys.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import com.example.utils.jwtutil;
import com.example.utils.redisutils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户登录服务
 */
@Service
public class UserServiceImp extends ServiceImpl<UserMapper, User> implements UserService {
  final
  UserMapper userMapper;

    public UserServiceImp(UserMapper userMapper, redisutils redisutils) {
        this.userMapper = userMapper;
        this.redisutils = redisutils;
    }
    final
    redisutils redisutils;

    @Override
    public String login(User user) {
        String username = user.getUsername();
       User u  =  userMapper.login(username);
       if (u==null){
           throw new RuntimeException("没有账户");
       }
       else {
           Map<String,Object> map = new HashMap<>();
           map.put("id",u.getId());
           String token = jwtutil.CreateJwt(map, "key");

           LoginUser loginUser = new LoginUser();

           BeanUtils.copyProperties(u,loginUser);

           Long start = System.currentTimeMillis();

           Long end = start+60*60*1000;

           loginUser.setStartTime(start);

           loginUser.setEndTime(end);
           redisutils.setEx(u.getId().toString(), JSON.toJSONString(loginUser),60*60*1000, TimeUnit.MILLISECONDS);

           return token;
       }
    }
}
